<template>
  <div class="ClosingTime">
    <!-- https://api.kuaipaoya.cn/profile/2025/10/21/bj_20251021204752A001.jpg -->
    <image src="https://api.kuaipaoya.cn/profile/2025/10/21/bj_20251021204752A001.jpg" alt="关闭时间"></image>
    <div class="tips">{{ title }}</div>


    <!-- 底部按钮 - 只有骑手才显示 -->
    <div class="action-area" v-if="userInfo.roleTypeId == 1">
      <button class="btn-primary" @click="goToOrderHall">
        前往接单大厅
      </button>
    </div>
    <div class="action-area" v-if="userInfo.roleTypeId == 4||userInfo.roleTypeId == 2">
      <button class="btn-primary" @click="showShopPopup = true">
        进入门店
      </button>
    </div>
    <!-- 店铺选择弹出层 -->
    <wd-popup v-model="showShopPopup" position="bottom">
      <view class="shop-popup">
        <view class="shop-popup-title">选择店铺</view>
        <view class="shop-list">
          <view v-for="(shop, idx) in myShopList" :key="idx" class="shop-item" @click="selectShop(shop)">
            <!-- <img style="width: 80rpx !important; height: 80rpx !important;" :src="shop.logo || '../static/imgs/NoPath.png'" class="shop-logo"></img> -->
            <view class="shop-info">
              <view class="shop-name">{{ shop.shopName }}</view>
              <view class="shop-type">{{ shop.shopType }}</view>
            </view>
            <wd-icon name="arrow-right" size="16px" color="#666"></wd-icon>
          </view>
        </view>
        <view class="close-btn" @click="showShopPopup = false">取消</view>
      </view>
    </wd-popup>
  </div>
</template>

<script setup>
import { ref, nextTick, onUnmounted } from 'vue'
import { onLoad, onShow, onHide } from '@dcloudio/uni-app'
import { useLoginStore } from '@/stores/login'
import { baseUrl } from '@/utils/config'

const title = ref('')
const loginStore = useLoginStore()
const userInfo = ref({})
const showShopPopup = ref(false)
const myShopList = ref([])

// ========== 新增：倒计时相关状态 ==========
const countdown = ref({
  hours: 0,
  minutes: 0,
  seconds: 0,
  total: 0
})
const countdownTimer = ref(null)
const recheckTimer = ref(null)
let isCheckingStatus = false  // 新增：防止重复检查
// ========================================
// ✅ 使用缓存管理弹窗状态（全局唯一）
const MODAL_CACHE_KEY = 'LOGIN_EXPIRED_MODAL_SHOWING'
const MODAL_TIMESTAMP_KEY = 'LOGIN_EXPIRED_MODAL_TIME'

// 检查是否正在显示弹窗
const isModalShowing = () => {
  const showing = uni.getStorageSync(MODAL_CACHE_KEY)
  const timestamp = uni.getStorageSync(MODAL_TIMESTAMP_KEY)

  // 如果超过5秒还在显示状态，可能是异常，重置
  if (showing && timestamp && Date.now() - timestamp > 5000) {
    clearModalCache()
    return false
  }

  return showing === 'true'
}
onShareAppMessage(() => {
  return {
    title: '快跑吖-校园外卖平台',
    path: '/pages/index',
    imageUrl: '/static/imgs/logo.jpg',
  }
})
// 设置弹窗显示状态
const setModalShowing = (showing) => {
  if (showing) {
    uni.setStorageSync(MODAL_CACHE_KEY, 'true')
    uni.setStorageSync(MODAL_TIMESTAMP_KEY, Date.now())
  } else {
    clearModalCache()
  }
}

// 清除弹窗缓存
const clearModalCache = () => {
  uni.removeStorageSync(MODAL_CACHE_KEY)
  uni.removeStorageSync(MODAL_TIMESTAMP_KEY)
}

// ✅ 防止重复加载
let isLoading = false

// ✅ 添加生命周期日志，检查触发次数
onLoad((options) => {
  console.log('🔵 onLoad 触发', Date.now(), options)

  if (isLoading) {
    console.log('⚠️ onLoad 重复触发，已忽略')
    return
  }
  isLoading = true

  title.value = options?.title || ''

  nextTick(() => {
    initPage()
  })
})
// 在组件挂载时从缓存加载数据
onMounted(() => {
  // 从本地缓存获取数据
  try {
    const cachedData = uni.getStorageSync('my-shop-list-cache')
    if (cachedData) {
      myShopList.value = JSON.parse(cachedData)
      console.log('bottomNav: 从缓存加载店铺数据成功', myShopList.value)
    } else {
      console.log('bottomNav: 缓存中没有店铺数据')
      // 如果缓存中没有数据，尝试使用 store 中的数据
      if (userStore.myShopList && userStore.myShopList.length > 0) {
        myShopList.value = userStore.myShopList
      }
    }
  } catch (error) {
    console.error('bottomNav: 读取缓存数据失败', error)
  }
})

// 选择店铺
const selectShop = (shop) => {
  console.log('选择店铺', shop)
  showShopPopup.value = false
  // 导航到店铺页面
  uni.navigateTo({
    url: `/pages/shopManage?shopId=${shop.shopId}`
  })
  // 设置导航栏激活项
}
// ✅ 监控 onShow 是否触发
onShow(() => {
  console.log('🟢 onShow 触发', Date.now())

  // ========== 新增：页面显示时重新检查营业状态 ==========
  if (!isLoading) {
    // 重置检查标志位，允许重新检查
    isCheckingStatus = false

    // 重新检查营业状态
    checkOperatingStatus()
  }
  // =================================================
})

// ========== 新增：页面隐藏时清除定时器 ==========
onHide(() => {
  console.log('🔴 onHide 触发，清除定时器')

  // 清除倒计时定时器
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
    countdownTimer.value = null
  }

  // 清除重试定时器
  if (recheckTimer.value) {
    clearTimeout(recheckTimer.value)
    recheckTimer.value = null
  }

  // 重置倒计时显示
  countdown.value = {
    hours: 0,
    minutes: 0,
    seconds: 0,
    total: 0
  }
})
// ============================================

// ✅ 页面初始化逻辑
const initPage = async () => {
  try {
    // 先获取用户信息
    await getUserInfo()

    await getShopClassList()
  } catch (error) {
    console.error('页面初始化失败:', error)
  } finally {
    isLoading = false
  }
}
const operatingTime = ref([])
const getShopClassList = async () => {
  // 修改这一行：移除 isLoading 检查
  if (isModalShowing()) return  // 原来是：if (isModalShowing() || isLoading) return

  try {
    const header = {}
    if (loginStore.token) {
      header.accesstoken = loginStore.token
    }

    const response = await new Promise((resolve, reject) => {
      uni.request({
        url: `${baseUrl}shopping/ShopCategory/list`,
        method: 'GET',
        header: header,
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })

    if (response?.data?.code === 200) {
      setTimeout(() => {
        uni.reLaunch({
          url: `/pages/index`,
        })
      }, 100)
    } else if (response?.data?.code === 10001) {
      title.value = response.data.msg
      operatingTime.value = JSON.parse(response.data.data.operatingTime) || []
      console.log('------------->', operatingTime.value)

      // ========== 新增：触发营业状态检查 ==========
      checkOperatingStatus()
      // =========================================
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

const getUserInfo = async () => {
  // ✅ 如果已经在显示弹窗，直接返回
  if (isModalShowing()) {
    console.log('⚠️ 弹窗已显示，跳过 getUserInfo')
    return
  }

  try {
    const header = {}
    if (loginStore.token) {
      header.accesstoken = loginStore.token
    }

    const result = await new Promise((resolve, reject) => {
      uni.request({
        url: `${baseUrl}shopping/login/getUserInfo`,
        method: 'GET',
        header: header,
        success: (res) => resolve(res),
        fail: (err) => reject(err),
        timeout: 10000
      })
    })

    if (result?.data?.code === 200) {
      userInfo.value = result.data.data || {}
    } else if (result?.data?.code === 403) {
      // 获取系统信息
      const systemInfo = wx.getSystemInfoSync();
      if (systemInfo.platform == 'ios' || systemInfo.platform == 'androdevtoolsid') {
        uni.showModal({
          title: '提示',
          content: '登录已过期，请重新登录',
          showCancel: true,
          success: (res) => {
            if (res.confirm) {
              // ✅ 延迟跳转
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/login'
                })
              }, 100)
            }
          },
          fail: (err) => {
            console.error('显示弹窗失败:', err)
            // clearModalCache()
          },
          complete: () => {
            // ✅ 弹窗关闭后延迟清除标记（仅作为备份，主要在 success 中清除）
            setTimeout(() => {
              // 如果用户已经跳转，这里不需要再清除
              clearModalCache()
            }, 500)
          }
        })
      } else {

        // ✅ 登录过期处理
        console.log('🔴 检测到登录过期 403')
        showLoginExpiredModal()
      }
      console.log(systemInfo, '系统信息查看')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// ✅ 提取弹窗逻辑为独立函数，使用缓存控制
const showLoginExpiredModal = () => {
  console.log('🟡 showLoginExpiredModal 调用', isModalShowing())

  // ✅ 双重检查，防止重复弹窗
  if (isModalShowing()) {
    console.log('⚠️ 弹窗已显示，取消本次弹窗')
    return
  }

  // ✅ 立即设置缓存标记
  setModalShowing(true)

  // ✅ 使用 setTimeout 确保在下一个事件循环中执行
  setTimeout(() => {
    uni.showModal({
      title: '提示',
      content: '登录已过期，请重新登录',
      showCancel: true,  // ✅ 不显示取消按钮，避免用户不操作
      success: (res) => {
        if (res.confirm) {

          // ✅ 延迟跳转
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login'
            })
          }, 100)
        }
      },
      fail: (err) => {
        console.error('显示弹窗失败:', err)
        // clearModalCache()
      },
      complete: () => {
        // ✅ 弹窗关闭后延迟清除标记（仅作为备份，主要在 success 中清除）
        setTimeout(() => {
          // 如果用户已经跳转，这里不需要再清除
          clearModalCache()
        }, 500)
      }
    })
  }, 100)
}

const goToOrderHall = () => {
  // ✅ 防抖处理
  if (isModalShowing() || isLoading) return

  uni.navigateTo({
    url: '/pages/OrderReceptionHall'
  })
}

// ========== 新增：营业时间判断和倒计时方法 ==========

/**
 * 获取当前时间的总秒数（从00:00:00开始）
 */
const getCurrentSeconds = () => {
  const now = new Date()
  return now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds()
}

/**
 * 将时间字符串转换为秒数
 */
const timeToSeconds = (timeStr) => {
  const [hours, minutes] = timeStr.split(':').map(Number)
  return hours * 3600 + minutes * 60
}

/**
 * 判断当前时间是否在营业时间段内
 */
const isInOperatingTime = (operatingTimes) => {
  const currentSeconds = getCurrentSeconds()

  return operatingTimes.some(period => {
    const start = timeToSeconds(period.startTime)
    const end = timeToSeconds(period.endTime)
    return currentSeconds >= start && currentSeconds < end
  })
}

/**
 * 获取距离下一个营业时间的秒数
 */
const getMinutesToNextOperating = (operatingTimes) => {
  const currentSeconds = getCurrentSeconds()
  let minDiff = Infinity

  // 查找今天剩余的营业时间
  operatingTimes.forEach(period => {
    const start = timeToSeconds(period.startTime)
    if (start > currentSeconds) {
      const diff = start - currentSeconds
      if (diff < minDiff) {
        minDiff = diff
      }
    }
  })

  // 如果今天没有剩余营业时间，计算到明天第一个营业时间
  if (minDiff === Infinity && operatingTimes.length > 0) {
    const earliestTime = Math.min(...operatingTimes.map(p => timeToSeconds(p.startTime)))
    minDiff = (24 * 3600 - currentSeconds) + earliestTime  // 改为秒数计算
  }

  return minDiff  // 直接返回秒数
}

/**
 * 开始倒计时
 */
const startCountdown = (totalSeconds) => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }

  let remaining = totalSeconds

  const updateDisplay = () => {
    const hours = Math.floor(remaining / 3600)
    const minutes = Math.floor((remaining % 3600) / 60)
    const seconds = remaining % 60

    countdown.value = {
      hours,
      minutes,
      seconds,
      total: remaining
    }

    // ========== 新增：每秒打印倒计时 ==========
    console.log(`⏰ 倒计时更新: ${hours}时${minutes}分${seconds}秒 (剩余${remaining}秒)`)
    // ======================================
  }

  updateDisplay()

  countdownTimer.value = setInterval(() => {
    remaining--

    if (remaining <= 0) {
      clearInterval(countdownTimer.value)
      console.log('⏰ 倒计时结束，重新检查营业状态')

      // ========== 修改：重置标志位后再调用 ==========
      isCheckingStatus = false
      checkOperatingStatus()
      // ==========================================
    } else {
      updateDisplay()
    }
  }, 1000)
}

/**
 * 检查营业状态的主方法
 */
const checkOperatingStatus = async () => {
  // ========== 新增：防止重复调用 ==========
  if (isCheckingStatus) {
    console.log('⚠️ 正在检查营业状态，跳过重复调用')
    return
  }
  isCheckingStatus = true
  // ====================================

  if (recheckTimer.value) {
    clearTimeout(recheckTimer.value)
  }

  try {
    if (operatingTime.value && operatingTime.value.length > 0) {
      if (isInOperatingTime(operatingTime.value)) {
        console.log('✅ 当前在营业时间内，跳转首页')
        uni.reLaunch({
          url: '/pages/index'
        })
        return
      } else {
        const minutesToNext = getMinutesToNextOperating(operatingTime.value)
        console.log(`⏳ 距离下次营业还有 ${Math.floor(minutesToNext / 60)} 分钟 (${minutesToNext} 秒)`)

        if (minutesToNext < Infinity) {
          startCountdown(minutesToNext)
          // ========== 修改：已经启动倒计时，不需要再调用接口 ==========
          isCheckingStatus = false
          return  // 直接返回，不再调用 getShopClassList
          // =======================================================
        }
      }
    }

    // 只有在没有营业时间数据，或者倒计时结束时才调用接口
    await getShopClassList()

  } catch (error) {
    console.error('检查营业状态失败:', error)
    recheckTimer.value = setTimeout(() => {
      checkOperatingStatus()
    }, 5 * 60 * 1000)
  } finally {
    // ========== 新增：重置标志位 ==========
    isCheckingStatus = false
    // ===================================
  }
}

// 清理定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
  if (recheckTimer.value) {
    clearTimeout(recheckTimer.value)
  }
})

// ========================================
</script>

<style lang="scss" scoped>
.ClosingTime {
  min-height: 100vh;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
  position: relative;

  image {
    flex: 1;
    width: 100%;
    min-height: 100vh;
    background: url("https://api.kuaipaoya.cn/profile/2025/10/21/bj_20251021204752A001.jpg") no-repeat center center;
    background-size: 100% 100%;
  }

  .tips {
    position: absolute;
    top: 33%;
    left: 50%;
    width: 350rpx;
    transform: translateX(-50%);
    text-align: center;
    font-size: 28rpx;
    font-weight: bold;
  }

  /* ========== 新增：倒计时样式 ========== */
  .countdown-display {
    position: absolute;
    top: 45%;
    left: 50%;
    transform: translateX(-50%);
    text-align: center;

    .countdown-text {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 20rpx;
    }

    .countdown-time {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10rpx;

      .time-unit {
        display: flex;
        flex-direction: column;
        align-items: center;

        .number {
          font-size: 48rpx;
          font-weight: bold;
          color: #667eea;
          background: rgba(255, 255, 255, 0.9);
          padding: 10rpx 20rpx;
          border-radius: 12rpx;
          min-width: 80rpx;
          text-align: center;
        }

        .label {
          font-size: 24rpx;
          color: #999;
          margin-top: 8rpx;
        }
      }

      .separator {
        font-size: 40rpx;
        font-weight: bold;
        color: #667eea;
        margin: 0 8rpx;
      }
    }
  }
  /* ====================================== */

  .action-area {
    position: absolute;
    bottom: 100rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 100%;
    padding: 0 60rpx;
    box-sizing: border-box;

    .btn-primary {
      width: 100%;
      height: 88rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 44rpx;
      border: none;
      color: #fff;
      font-size: 32rpx;
      font-weight: bold;
      box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);

      &:active {
        opacity: 0.8;
      }
    }
  }

  .shop-logo {
    width: 80rpx !important;
    height: 80rpx !important;
    border-radius: 16rpx;
    margin-right: 20rpx;
  }

  /* 店铺选择弹出层样式 */
  .shop-popup {
    background-color: #fff;
    border-radius: 24rpx 24rpx 0 0;
    padding: 30rpx;


    .shop-popup-title {
      font-size: 32rpx;
      font-weight: bold;
      text-align: center;
      padding-bottom: 20rpx;
      border-bottom: 1px solid #f5f5f5;
      margin-bottom: 10rpx;
    }

    .shop-list {
      max-height: 60vh;
      overflow-y: auto;

      .shop-item {
        display: flex;
        align-items: center;
        padding: 24rpx 0;
        border-bottom: 1px solid #f5f5f5;


        .shop-info {
          flex: 1;

          .shop-name {
            font-size: 28rpx;
            font-weight: 500;
            color: #333;
            margin-bottom: 8rpx;
          }

          .shop-type {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }

    .close-btn {
      margin-top: 30rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background: #f5f5f5;
      border-radius: 40rpx;
      font-size: 28rpx;
      color: #666;
    }
  }
}
</style>
